﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NMemcached.Client
{
    /// <summary>
    /// A container for extension methods. This class is not intented to be used directly.
    /// </summary>
    public static class ExtensionMethods
    {
        static ExtensionMethods()
        {
        }

        /// <summary>
        /// Calculates the key distribution percentages for an IConnectionProvider instance
        /// </summary>
        /// <param name="connectionProvider">The IConnectionProvider being tested</param>
        /// <param name="keys">The keys for which the statistics are calculated</param>
        /// <returns>A collection that contains the percentage of keys distributed to each server</returns>
        /// <remarks>
        /// <para>The distribution percentages are determined by calling IConnectionProvider.GetConnection for each key specified. No commands are sent though the connection returned.</para>
        /// </remarks>
        public static IDictionary<ServerConnection, float> CalculateDistributionStatistics(this IConnectionProvider connectionProvider, IEnumerable<string> keys)
        {
            if (keys == null)
            {
                throw new ArgumentNullException("keys");
            }

            //Initialize all the counts to zero
            Dictionary<ServerConnection, int> counts = new Dictionary<ServerConnection, int>();
            foreach (ServerConnection server in connectionProvider.Servers)
            {
                counts.Add(server, 0);
            }
            //Get the total number of keys
            int keyCount = keys.Count();

            ServerConnection currentCon = null;
            //Collect the counts per server
            foreach (string key in keys)
            {
                currentCon = connectionProvider.GetConnection(key);
                counts[currentCon]++;
            }

            //Calculate the percentages per server
            Dictionary<ServerConnection, float> percentages = new Dictionary<ServerConnection, float>();
            float percentage;
            foreach (KeyValuePair<ServerConnection, int> keyCountPair in counts)
            {
                percentage = ((float)keyCountPair.Value / (float)keyCount) * 100;
                percentages.Add(keyCountPair.Key, percentage);
            }

            return percentages;
        }
    }
}
